from flask_restx import Namespace, Resource, reqparse
from flask import request
from models.investment import Investment
from extensions import db
from utils.auth import token_required
from models.store import Store
from models.user import User
import uuid

api = Namespace('investments', description='投资相关操作')

@api.route('/')
class InvestmentList(Resource):
    @token_required
    def get(self):
        """获取所有投资记录"""
        investments = Investment.query.options(db.joinedload(Investment.store), db.joinedload(Investment.investor)).all()
        return {
            'status': 'success',
            'data': [investment.to_dict() for investment in investments]
        }, 200

    @token_required
    def post(self):
        """创建新投资记录"""
        data = request.get_json()
        
        # 检查必填字段
        required_fields = ['store_id', 'investor_id', 'amount', 'type', 'date']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        
        # 验证店铺和投资人是否存在
        store = Store.query.filter_by(store_id=data['store_id'], is_deleted=False).first()
        if not store:
            return {
                'status': 'error',
                'message': '指定的店铺不存在'
            }, 400
            
        investor = User.query.filter_by(user_id=data['investor_id'], is_deleted=False).first()
        if not investor:
            return {
                'status': 'error',
                'message': '指定的投资人不存在'
            }, 400
        
        # 创建新投资记录
        new_investment = Investment(
            investment_id=str(uuid.uuid4()),
            store_id=data['store_id'],
            investor_id=data['investor_id'],
            amount=data['amount'],
            type=data['type'],
            date=data['date'],
            description=data.get('description')
        )
        
        db.session.add(new_investment)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '投资记录创建成功',
            'data': new_investment.to_dict()
        }, 201

@api.route('/<investment_id>')
class InvestmentDetail(Resource):
    @token_required
    def get(self, investment_id):
        """获取单个投资记录"""
        investment = Investment.query.options(db.joinedload(Investment.store), db.joinedload(Investment.investor)).get_or_404(investment_id)
        return {
            'status': 'success',
            'data': investment.to_dict()
        }, 200

    @token_required
    def put(self, investment_id):
        """更新投资记录"""
        investment = Investment.query.get_or_404(investment_id)
        data = request.get_json()
        
        # 更新投资记录
        if 'amount' in data:
            investment.amount = data['amount']
        if 'type' in data:
            investment.type = data['type']
        if 'date' in data:
            investment.date = data['date']
        if 'description' in data:
            investment.description = data['description']
        
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '投资记录更新成功',
            'data': investment.to_dict()
        }, 200

    @token_required
    def delete(self, investment_id):
        """删除投资记录"""
        investment = Investment.query.get_or_404(investment_id)
        
        db.session.delete(investment)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '投资记录删除成功'
        }, 200